<template lang="">
  <div class="add-class-page" style="width:100vw;overflow:hidden;">
    <!-- 头部 -->
    <!-- <div style="padding-top: 40px;">
      <mt-header fixed title="申请开课">
        <router-link to="/StudyCenter" slot="left">
          <mt-button icon="back"></mt-button>
        </router-link>
      </mt-header>
    </div> -->
    <div class="bscroll" ref="bscroll0">
      <div class="bscroll-container">
        <div class="form-body">
          <div style="background-color: #ffffff;">
            <form class="form-box" action="">
              <div class="input-item flex-row">
                <label for="title"><span class="add-course-icon iconfont iconzhuti-"></span>课程主题</label>
                <input v-model="title" placeholder="请输入课程主题" name="title" type="text">
              </div>
              <div class="input-item flex-row">
                <label for="smallTitle"><span class="add-course-icon iconfont iconshuoming"></span>课程说明</label>
                <input v-model="smallTitle" placeholder="请输入课程说明" name="smallTitle" type="text">
              </div>
              <div class="input-item flex-row">
                <label for="courseTime"><span style="font-size:0.47rem;" class="add-course-icon iconfont iconloudou"></span>课程时长</label>
                <div style="flex: 1 0 auto;text-align: right;">
                  <input v-model="courseTime" placeholder="请输入时长" name="courseTime" type="text">
                  <span>min</span>
                </div>
              </div>
              <div class="input-item flex-row">
                <label for="date"><span class="add-course-icon iconfont iconiconfront-"></span>日期</label>
                <input @click="handleCommentFocus" :start-date="startDate" v-model="date" readonly placeholder="请选择日期"
                  name="date" type="text">
              </div>
              <div class="input-item flex-row">
                <label for="time"><span class="add-course-icon iconfont icondengdai"></span>时间</label>
                <input v-model="time" @click="handleCommentClick" readonly placeholder="请选择时间" name="time" type="text">
              </div>
              <div class="input-item flex-row">
                <label for="address"><span class="add-course-icon iconfont icondidian"></span>地点</label>
                <input placeholder="请输地点" v-model="address" name="address" type="text">
              </div>
              <div @click="checkPopup('')" class="input-item flex-row">
                <label for="students"><span class="add-course-icon iconfont iconxingming"></span>授课对象</label>
                <input v-model="studyName" placeholder="请选择授课对象" name="students" readonly type="text">
              </div>
              <div class="input-item flex-row">
                <label for="courseName"><span style="font-size:15px;top:0;letf:2px;margin-right:14px;" class="add-course-icon iconfont iconleibie"></span>课程类别</label>
                <input @click="courseTypes" placeholder="请选择课程类别" readonly v-model="courseName" name="courseName"
                  type="text">
              </div>
              <div class="input-item flex-row">
                <label for="flag"><span class="add-course-icon iconfont iconshuangxiangzhuanzhen"></span>是否公开</label>
                <mt-switch v-model="flag" @change="switchChoose"></mt-switch>
              </div>
              <div class="input-item flex-row">
                <label for="num"><span class="add-course-icon iconfont iconrenshu"></span>人数限制</label>
                <div style="flex: 1 0 auto;text-align: right;">
                  <input v-model="num" placeholder="请输人数" name="num" type="text">
                  <span>人</span>
                </div>              
              </div>
            </form>
          </div>
          <div class="class-detail">
            <div class="class-tips">课程简介</div>
            <div class="class-content">
              <textarea v-model="introduce" placeholder="请输课程简介..." style="width: 100%;height: 100px;outline: none;"
                name="" id="" cols="30" rows="10"></textarea>
            </div>
          </div>
          <div style="padding-top:0;margin-top:-10px;" class="class-detail">
            <div class="class-tips">宣传图片</div>
            <div class="class-content">
              <van-uploader
                v-model="fileList"
                :max-count="1"
                :after-read="afterRead"
                :before-delete="beforeDel"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <mt-datetime-picker
    :startDate="new Date(new Date().setDate(new Date().getDate()+1))"
    @confirm="handleConfirm" ref="pickerDate" type="date" year-format="{value} 年"
      month-format="{value} 月" date-format="{value} 日">
    </mt-datetime-picker>

    <mt-datetime-picker @confirm="handleTimeConfirm" ref="pickerTime" type="time" hourFormat="{value} 点"
      minuteFormat="{value} 分">
    </mt-datetime-picker>
    <mt-popup v-model="flagPicker" position="bottom">
      <div class="init-btn flex-row">
        <div @click="pickerBtn(1)" class="close">取消</div>
        <div @click="pickerBtn(2)" class="confirm">确认</div>
      </div>
      <mt-picker valueKey="name" :slots="slots" @change="flagPickerChange">

      </mt-picker>
    </mt-popup>
    <mt-popup v-model="courseTypePicker" position="bottom">
      <div class="init-btn flex-row">
        <div @click="pickerBtn(3)" class="close">取消</div>
        <div @click="pickerBtn(4)" class="confirm">确认</div>
      </div>
      <mt-picker valueKey="name" :slots="courseTypeSlots" @change="courseTypeChange">

      </mt-picker>
    </mt-popup>
    <mt-popup v-model="checkPopupModal" position="right">
      <mt-search v-model="searchVal" cancel-text="取消" placeholder="搜索"></mt-search>
      <div style="overflow:auto;height:82vh;">
        <div class="default-page-box" v-show="prelectObject.length == 0">
          <div class="default-page">
            <div class="default-text">哎呀，空空如也!</div>
          </div>
        </div>
        <van-collapse :value="activeName" @change="onChange" accordion>
          <van-collapse-item v-for="(item,index) in prelectObject" :key="index"  :title="item.name" :name="item.ddId">
            <mt-checklist title="授课对象" v-model="students" :options="options"></mt-checklist>
          </van-collapse-item>
        </van-collapse>
      </div>
      <div class="popup-btn flex-row">
        <mt-button style="margin-right:20px;" size="large" @click="closePopup">取消</mt-button>
        <mt-button @click="confirmPopup" size="large" type="primary">确定</mt-button>
      </div>
    </mt-popup>
    <div class="footer-button">
      <mt-button :disabled='canClick' @click="addClass" size="large" type="primary">申请开课</mt-button>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
import DdValidate from "../../untils/validate";
import { Indicator, Toast } from "mint-ui";
import { setText } from "../../untils/ddnavigate";
const easydate = require("../../untils/easydate");
const nature = require("../../untils/antiShaking");
export default {
  data() {
    return {
      canClick: false,
      uploadFile: "", // 文件上传
      fileList: [], // 宣传图片
      searchVal: "", // 搜索授课对象值
      activeName: "",
      studyName: "", // 学习对象名字
      students: [],
      options: [],
      studentData: [], // 授课对象
      prelectObject: [], // 授课对象对应部门
      allOptions: [], // 所有授课对象
      title: "",
      smallTitle: "",
      courseTime: "",
      date: "",
      time: "",
      address: "",
      courseName: "",
      courseNameChecked: "",
      courseType: "0",
      flag: false,
      flagCn: "",
      num: "",
      introduce: "",
      studentsName: "公开",
      studentsChecked: "",
      startDate: "",
      checkPopupModal: false, // 授课对象选择框
      flagPicker: false, // 授课对象picker
      courseTypePicker: false, // 课程类别picker
      slots: [
        {
          values: [
            {
              name: "公开",
              num: 0
            },
            {
              name: "不公开",
              num: 1
            }
          ],
          flex: 1
        }
      ],
      courseTypeSlots: [
        {
          values: [
            {
              name: "部门课程",
              courseDept: 0
            },
            {
              name: "公司级别课程",
              courseDept: 1
            }
          ],
          flex: 1
        }
      ]
    };
  },
  mounted() {
    const rules = {
      title: {
        required: true
      },
      smallTitle: {
        required: true
      },
      courseTime: {
        number: true,
        required: true
      },
      date: {
        required: true
      },
      time: {
        required: true
      },
      address: {
        required: true
      },
      courseName: {
        required: true
      },
      num: {
        required: true,
        digits: true
      },
      introduce: {
        required: true
      }
    };

    const messages = {
      title: {
        required: "请填写课程主题"
      },
      smallTitle: {
        required: "请填写课程说明"
      },
      courseTime: {
        number: "课程时长请输入有效数字",
        required: "请填写课程时长"
      },
      date: {
        required: "请选择日期"
      },
      time: {
        required: "请填写时间"
      },
      num: {
        required: "请填写人数限制",
        digits: "人数请输入整数"
      },
      address: {
        required: "请填写地址"
      },
      courseName: {
        required: "请选择课程类别"
      },
      introduce: {
        required: "请填课程简介"
      }
    };
    setText("申请开课");
    // better-scroll初始化
    this.initScroll("bscroll0");
    // 实例化一个校验对象;
    this.Validate = new DdValidate(rules, messages);
    // 取当前时间
    let edate = easydate(new Date());
    this.startDate = edate.format("yyyy/MM/dd");
  },
  watch: {
    students(before, after) {},
    searchVal(before, after) {
      console.log(before);
      this.checkPopup(before);
    }
  },
  methods: {
    afterRead(file) {
      this.uploadFile = file.file;
      console.log(file);
    },
    beforeDel(file) {
      this.uploadFile = "";
      console.log(file);
      return true;
    },
    onChange(event) {
      this.activeName = event;
      if (event) {
        this.openCell(event);
      }
    },
    initScroll(dom) {
      this.$nextTick(() => {
        let bscrollDom = this.$refs[dom];
        this.aBScroll = new BScroll(bscrollDom, {
          click: true
        });
      });
    },
    closePopup() {
      this.checkPopupModal = false;
      this.students = [];
    },
    confirmPopup() {
      this.checkPopupModal = false;
      let students = this.students;
      let allOptions = this.allOptions;
      let result = [];
      students.map(function(students) {
        allOptions.map(function(item) {
          if (students == item.value) {
            result.push(item.label);
          }
        });
      });
      this.studyName = result;
    },
    openCell(id) {
      let { searchVal } = this;
      let params = {
        id,
        userName: searchVal
      };
      this.$get("qryCourseDeptUserList", params).then(res => {
        let optionArr = [];
        if (res.success) {
          this.studentData = res.data;
          if (res.data.length > 0) {
            res.data.map(function(item) {
              optionArr.push({
                label: item.username,
                value: item.id
              });
            });
          }
          this.options = optionArr;
          this.allOptions = this.allOptions.concat(optionArr);
        }
      });
    },
    checkPopup(searchVal) {
      let params = {
        id: "",
        userName: searchVal
      };
      this.$get("qryCourseDeptMessage", params).then(res => {
        if (res.success) {
          this.prelectObject = res.data;
          this.checkPopupModal = true;
        } else {
          Toast({
            message: "数据获取失败",
            duration: 2000
          });
        }
      });
    },
    switchChoose() {
      if (this.flag) {
      }
    },
    handleConfirm(e) {
      this.date = easydate(e).format("yyyy-MM-dd");
    },
    handleTimeConfirm(e) {
      this.time = e;
    },
    handleCommentFocus() {
      this.$refs.pickerDate.open();
    },
    handleCommentClick() {
      this.$refs.pickerTime.open();
    },
    flagPickerChange(picker, value) {
      this.studentsChecked = value[0].name;
    },
    courseTypeChange(picker, value) {
      this.courseNameChecked = value[0].name;
      this.courseDept = value[0].courseDept;
    },
    flagPickers() {
      this.flagPicker = true;
    },
    courseTypes() {
      this.courseTypePicker = true;
    },
    pickerBtn(num) {
      // num = 1 授课对象取消 num=2 授课对象确认 num=4 课程类别取消 num=4课程类别确认
      let that = this;
      let { studentsChecked, courseNameChecked } = this;
      switch (num) {
        case 1:
          that.flagPicker = false;
          break;
        case 2:
          that.flagPicker = false;
          that.studentsName = studentsChecked;
          break;
        case 3:
          that.courseTypePicker = false;
          break;
        default:
          that.courseTypePicker = false;
          that.courseName = courseNameChecked;
      }
    },
    addClass() {
      let {
        title,
        smallTitle,
        date,
        time,
        address,
        students,
        flag,
        num,
        introduce,
        courseTime,
        courseType,
        courseDept,
        studyName,
        courseName
      } = this;
      let params = {
        title,
        smallTitle,
        date,
        time,
        address,
        students,
        flag: flag ? 1 : 0,
        num,
        introduce,
        courseTime,
        courseType,
        courseDept,
        courseName
      };
      if (studyName.length > Number(num)) {
        Toast({
          message: "人数限制须多于授课对象",
          duration: 2000
        });
        return;
      }
      if (!this.uploadFile) {
        Toast({
          message: "请上传宣传图片",
          duration: 2000
        });
        return false;
      }
      if (!this.Validate.checkForm(params)) {
        const error = this.Validate.errorList[0];
        Toast({
          message: error.msg,
          duration: 2000
        });
        return false;
      }
      let formdata = new FormData();
      for (var key in params) {
        formdata.append(key, params[key]);
      }
      formdata.append("photoFile", this.uploadFile);
      let config = {
        header: {
          "Content-Type": "mutipart/form-data"
        }
      };
      Indicator.open({
        text: "加载中..."
      });
      this.canClick = true;
      this.$http.post("/course/addCourse", formdata, config).then(res => {
        if (res.data.success) {
          Indicator.close();
          Toast({
            message: "操作成功",
            iconClass: "mint-toast-icon mintui mintui-success",
            duration: 2000
          });
          setTimeout(() => {
            this.$router.go(-1);
            this.canClick = false;
          }, 2000);
        } else {
          Indicator.close();
          Toast({
            message: "操作失败",
            duration: 2000
          });
          this.canClick = false;
          return;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
@import url("~@/pagecss/addClass.less");
.add-course-icon {
  position: relative;
  top: 2px;
  margin-right: 10px;
  font-size: 40/75rem;
  color: #4787e4;
}
.bscroll-container {
  padding-bottom: 55px;
}
.default-page {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url("~@/assets/studyCenter/null.png") 50% 30% no-repeat;
  background-size: 352/75rem 215/75rem;
}
.default-text {
  left: 0;
  right: 0;
  position: absolute;
  top: 45%;
  text-align: center;
  font-size: 30/75rem;
  font-weight: 400;
  color: rgba(110, 176, 246, 0.7);
}
.popup-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30/75rem;
  justify-content: space-between;
  background-color: #ffffff;
}

.mint-popup-right {
  height: 100vh;
  width: 100vw;
}

.col-cell {
  width: 100%;
  border-top: 0.5px solid #eeeeee;
  border-bottom: 0.5px solid #eeeeee;
  background-color: #ffffff;
}

.col-cell-text {
  padding: 30/75rem 20/75rem;
  font-size: 30/75rem;
  font-weight: 500;
  border-bottom: 0.5px solid #eeeeee;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
  .fade-leave-to

  /* .fade-leave-active below version 2.1.8 */
 {
  opacity: 0;
}
</style>
